package com.java2007.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;

public class FileUtil {
    /**
     * 处理文件上传
     * @param request
     * @return
     * @throws Exception
     */
    public static String upload(HttpServletRequest request) throws Exception{
        String fileName = null;
        try {
            //   1.文件上传（1.获取图片名，截取后缀。）从HttpServletRequest中获取文件信息处理
            Part Part = request.getPart("image");
            fileName = Part.getSubmittedFileName();
            //      #1.获取后缀-->.jpg
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //      #2.拼接UUID和后缀,-->uuid.jpg
            fileName = UUIDUtil.getFileName(suffixName);

            //  2 .获取到的路径是WEB-INF文件夹的上层目录的真实路径
            String imgPath = request.getSession().getServletContext().getRealPath("/files/");
            File file = new File(imgPath,fileName);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            //  3.拼接路经--> path + imgName
            Part.write(file.getPath());
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
